package com.xfzp.android.ms;

import com.xfzp.d3.Coord;
import com.xfzp.d3.Ray;
import com.xfzp.d3.World;

/**
 * 魔方
 * 
 * @author AndroidApe
 * @version 2011-11-11
 */
public class Kube extends World {
	public static final float cubeWidth = 0.63f;
	public static final float spaceWidth = 0.055f;

	private int[] cubeOrder;
	private Layers layers;// 绕每个轴可旋转的3个层，共9个层

	public Kube(int[] cubeOrder) {
		add(InitKube.initCubes());
		layers = new Layers();
	}

	/**
	 * 返回层顺序
	 * 
	 * @return
	 */
	public int[] getCubeOrder() {
		return cubeOrder;
	}

	/**
	 * 选择转动的层
	 * 
	 * @param ray
	 * @param dir
	 * @return
	 */
	public AbleLayer rayPickup(Ray ray, Coord dir) {
		return layers.rayPickup(this, ray, dir);
	}

	/**
	 * 旋转指定的活动层。如果没有旋转返回-1；否则累加每次旋转的角度，返回累加的和除以90度的值，并将余数继续累加
	 */
	public int roundAbleLayer(AbleLayer ableLayer) {
		float a = ableLayer.nextRotateAngle();
		if (a != 0) {
			Layer layer = layers.getLayer(ableLayer.getLayerId());
			layer.rotate(a);
			int rc = ableLayer.resumeHasRotateAngle();
			boolean cw = true;
			if (rc < 0) {
				rc = -rc;
				cw = false;
			}
			if (rc > 0) {
				for (int i = 0; i < rc; i++) {
					updateOrder(layer, cw);
				}
			}
			return rc;
		}
		return -1;
	}

	/**
	 * 更新层的顺序
	 * 
	 * @param layer
	 * @param cw
	 */
	private void updateOrder(Layer layer, boolean cw) {
		int[] cubeIndex = layer.getCubeIndex();
		int len = 8;
		if (cw) {
			int i = 2;
			int t0 = cubeOrder[cubeIndex[0]];
			int t1 = cubeOrder[cubeIndex[1]];
			for (; i < len; i++) {
				cubeOrder[cubeIndex[i - 2]] = cubeOrder[cubeIndex[i]];
			}
			cubeOrder[cubeIndex[i - 2]] = t0;
			cubeOrder[cubeIndex[i - 1]] = t1;
		} else {
			int i = len - 1;
			int t0 = cubeOrder[cubeIndex[i - 1]];
			int t1 = cubeOrder[cubeIndex[i]];
			for (; i > 1; i--) {
				cubeOrder[cubeIndex[i]] = cubeOrder[cubeIndex[i - 2]];
			}
			cubeOrder[cubeIndex[0]] = t0;
			cubeOrder[cubeIndex[1]] = t1;
		}
	}
}
